var defaultParameter = {
  pageInfo:
  {
    "pageNumber" : 1,
    "pageSize": 20
  },
  impleProjName:'',
  contractCode:'',
  contractName:''
};
var oldPayment=null;
function initTable(){
  var columns=[[
    {field:'impleProjId',title:'项目id',width:5,fitColumns:true,hidden:true,},
    {field:'impleProjName',title:'实施项目名称',title:"实施项目名称",width:140,resizable:true,align:'center'},
    // {field:'contractCode',title:'合同编号', width:$(this).width()*0.1,fitColumns:true,hidden:true,},
    // {field:'contractName',title:"合同名称",width:$(this).width()*0.1,fitColumns:true,},
      {field:'contractName',title:"合同名称",width:150,align:'center',
          formatter: function(value,row,index){
              return  '<div>【'+row.contractCode+'】'+row.contractName+'</div>'
          }},
    {field:'contractTotal',title:"总金额",width:120,resizable:true,align:'center'},
    //{field:'contractClauseName',title:'支付条款',width:$(this).width()*0.1,fitColumns:true,},
      {field:'contractClauseName',title:"支付条款",width:290,fitColumns:true,resizable:true,align:'left',
          formatter: function(value,row,index){
              if(value){
                  if(value.length > 120){
                      return "<span style='cursor:pointer'><a onclick='showSubjectContent(\""+row.contractName+"\",\""+ row.contractClauseId +"\")'>" + value.substr(0,65) + "...</a></span>";
                  }else{
                      // return "<a href='javascript:;' data-toggle='modal' onclick='com.im.contractSign.invoke.showSubjectContent("+ index +")'>" + value + "</a>";
                      return "<span style='cursor:pointer'><a onclick='showSubjectContent(\""+row.contractName+"\",\""+ row.contractClauseId +"\")'>" + value + "</a></span>";
                  }
              }
          }
      },
    {field:'contractItemName',title:"合同分项",width:100,resizable:true,align:'center'},
    {field:'amount',title:"数量",resizable:true,align:'center'},
    {field:'unitPrice',title:"单价",resizable:true,align:'center'},
    {field:'otherCharge',title:"其它费用",resizable:true,align:'center'},
    {field:'itemTotal',title:"分项总额",resizable:true,align:'center'},
    {field:'paymentRatio',title:"已支付比例",resizable:true,align:'center'},
    {field:'payment',title:"已支付金额",resizable:true,align:'center'},
    {field:'nowPaymentRatio',title:"当前<br>支付比例",resizable:true,align:'center'},
    {field:'nowPayment',title:"当前<br>支付金额",resizable:true,align:'center'},
    {field:'createDt',title:"申报时间",width:110,resizable:true,align:'center'},
    {field:'description',title:"备注",width:160,resizable:true,align:'center'},
    {field:'statusCdName',title:"状态",width:80,resizable:true,align:'center'},
    {field:'operation',title:"操作",width:80,align:'center',
      formatter: function(value,row,index){
    	if(row.statusCd == '50'){
    		return '';
    	}else{
	        return '<a class="edit" href="javascript:void(0)" title="编辑" onclick="updateContractItemModel('+ index+ ')"> <i class="fa fa-edit"></i></a>';
	//               '<a class="remove" href="javascript:void(0)" title="删除" onclick="delMeasureReportConfirm('+ index+ ')"><i class="fa fa-trash"></i></a>';
        }
    }},
  ]];

  $('#measureList').datagrid({
    url:'/InfoManageWeb/measureReportController/queryContractItemList',
    method:'post',
    dataType : 'json',
    queryParams:defaultParameter,
    pagination:true,
    nowrap:false,
    fitColumns:true,
    columns:columns,
    loadMsg:'数据加载中，请耐心等待',
    loadFilter:function(data){
      if(data.resultCode!=0){
        toastr.error(data.resultCode);
        return null;
      }else{
        return data.result;
      }
    },
    onLoadSuccess: function (data) {
        if (data.rows.length > 0) {
        	mergeCellsByField('measureList', "contractCode",'contractTotal,impleProjName,contractName,contractClauseName,operation');
        }
    }
  });
  var p = $('#measureList').datagrid('getPager');
  $(p).pagination({
    pageSize: 20,//每页显示的记录条数，默认为10
    pageList: [10,20,30],//可以设置每页记录条数的列表
    beforePageText: '第',//页数文本框前显示的汉字
    afterPageText: '页    共 {pages}  页',
    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    onSelectPage:function(pageNumber, pageSize){
      defaultParameter.pageInfo.pageNumber = pageNumber;
      defaultParameter.pageInfo.pageSize = pageSize;
      defaultParameter.impleProjId=$("#implProjectId option:selected").attr("value");
      defaultParameter.planProjClass=$("#planProjClass option:selected").attr("value");
      defaultParameter.orgId=$("#orgId option:selected").attr("value");
      $('#measureList').datagrid('reload',defaultParameter);
    }
  });
}
//合并单元格
function mergeCellsByField(tableID, fldList,other) {
	var Arr = fldList.split(",");  
    var dg = $('#' + tableID);  
    var fldName;  
    var RowCount = dg.datagrid("getRows").length;  
    var span;  
    var PerValue = "";  
    var CurValue = "";  
    var length = Arr.length - 1;  
    for (i = length; i >= 0; i--) {  
        fldName = Arr[i];  
        PerValue = "";  
        span = 1;  
        for (row = 0; row <= RowCount; row++) {  
            if (row == RowCount) {  
                CurValue = "";  
            }  
            else {  
                CurValue = dg.datagrid("getRows")[row][fldName];  
            } 
            if (PerValue === CurValue) {  
                span += 1;  
            }  
            else {  
                var index = row - span;  
                dg.datagrid('mergeCells', {  
                    index: index,  
                    field: fldName,  
                    rowspan: span,  
                    colspan: null  
                });  
                var name = other.split(","); 
                $.each(name,function (i,item){
                	dg.datagrid('mergeCells', {  
                        index: index,  
                        field: item,  
                        rowspan: span,  
                        colspan: null  
                    });
                });
                span = 1;  
                PerValue = CurValue;  
            }  
        }  
    }  
}
function updateContractItemModel(index){
  //支付金额和备注可修改
  var row = $('#measureList').datagrid('getData').rows[index];
  $('#contractItemModal').modal("show");
  $("#orgNameList").val(row.orgId).trigger("change");
  $("#implProjectList").val(row.impleProjId).trigger("change");
  $("#contractList").val(row.contractId).trigger("change");
  $("#contractClauseList").val(row.contractClauseName).attr('data-id',row.contractClauseId);
  //$("#contractItemList").val(row.contractItemId).trigger("change");
//  $("#amount").val(row.amount);
//  $("#unitPrice").val(row.unitPrice);
//  $("#payment").val(row.payment);
//  $("#declareId").val(row.declareId);
//  showItemInfo({contractItemId:row.contractItemId});
//  var currentCount=parseFloat($("#availableAmount").val())+parseFloat(row.payment);
    oldPayment=row.payment;
//  $("#availableAmount").val(currentCount);
//  $("#paymentRatio").val((row.payment/$('#total').val()*100));
    disableModelField();
}
/**
 * 支付条款
 * @param object
 * @private
 */
function showSubjectContent(contractName,contractClauseId) {
    var client = new com.im.common.ajax();
    var param= {};
    param.contractClauseId = contractClauseId;
    var resp = client.callAsJson("contractService/qryContractClauseDetail", param);
    if (!resp.success) {
        toastr.error(result.resultMsg);
        return;
    }
    $("#vContractClauseDetailName").text("【"+contractName+"】支付条款");
    $("#vContractClauseDetailNameContent").html(resp.result.contractClauseName);
    $("#contractClauseDetail").modal("show");
}

function disableModelField(){
  $("#orgNameList").prop("disabled", true);
  $("#implProjectList").prop("disabled", true);
  $("#contractList").prop("disabled", true);
  $("#contractClauseList").prop("disabled", true);
  $("#contractItemList").prop("disabled", true);
  $("#availableAmount").attr("readonly",true);
  $("#amount").attr("readonly",true);
  $("#unitPrice").attr("readonly",true);
}

function availableModelField(){
  $("#orgNameList").prop("disabled", false);
  $("#implProjectList").prop("disabled", false);
  $("#contractList").prop("disabled", false);
  $("#contractClauseList").prop("disabled", true);
  $("#contractItemList").prop("disabled", false);
  $("#availableAmount").attr("readonly",false);
  $("#amount").attr("readonly",false);
  $("#unitPrice").attr("readonly",false);
}

function saveMeasureReport(){
var client = new com.im.common.ajax();
  var declareId=$("#declareId").val();
  var url = "measureReportController/addMeasureReport";
  if (declareId != null && declareId != "") {
    url = "measureReportController/saveMeasureReport";
  }
  var formValidator = $('#contractItemForm').data('bootstrapValidator');
  formValidator.options.excluded = [':disabled', ':hidden', ':not(:visible)'];
  formValidator.validate();
  var param = {};
  if (formValidator.isValid()) {
    param.declareId=declareId;
    param.amount=$("#amount").val();
    param.total=$("#total").val();
    param.payment=$("#payment").val();
    param.contractItemId=$("#contractItemList").val();
    param.paymentRatio=$("#paymentRatio").val();
    param.statusCd=10;
    param.declarer="测试";
    param.description=$("#description").val();
    param.oldPayment=oldPayment;

   var result = client.callAsJson(url,param);
   if(!result.success){
       toastr.error(result.resultMsg);
     }else{
         $('#contractItemModal').modal('hide');
         queryMeasureList();
     }
}
}

function queryMeasureList(){
      defaultParameter.impleProjId=$("#implProjectId option:selected").attr("value");
      defaultParameter.planProjClass=$("#planProjClass option:selected").attr("value");
      defaultParameter.orgId=$("#orgId option:selected").attr("value");
    $('#measureList').datagrid("load",defaultParameter);
}

function delMeasureReportConfirm(index){
     var row = $('#measureList').datagrid('getData').rows[index];
     var param={};
     param.declareId=row.declareId;
     param.payment=row.payment;
     param.contractItemId=row.contractItemId;
    com.im.common.confirm('确认删除计量申报？',param,"delMeasureReport");
}

function delMeasureReport(param){
 var client = new com.im.common.ajax();
  var result = client.callAsJson("measureReportController/delMeasureReport",param);
    if(!result.success){
      toastr.error(result.resultMsg);
    }else{
     queryMeasureList();
    }
}

function reset(){
    $("#searchProjectName").val("");
    $("#contractNo").val("");
    $("#contractName").val("");
}

function initProjectList(){
	$("#orgNameList").project2unit2itemCommpent({
		elmIdPlanTypeSel : "planProjClassList",
        elmIdUnitSel : "orgNameList",//组织单位下拉元素
        elmIdItemSel : "implProjectList",//实施项目下拉元素
        orgType : "10",//初始化单位时，单位类型
        callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            //_callBackOrg(objvalue, objname);
            //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
            //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
        }
    });
//  var client = new com.im.common.ajax();
//  var result = client.callAsJson("measureReportController/queryImplProjectList",null);
//  console.log(result);
//  if(!result.success){
//    toastr.error(result.resultMsg);
//  }else{
//     result.result.unshift({'impleProjId':'','impleProjName':'全部'});
//    $.each( result.result, function (i) {
//      $('#implProjectList').append("<option value=" + result.result[i].impleProjId + ">" +result.result[i].impleProjName + "</option>");
//
//    });
//    $("#implProjectList").select2({});
//    $("#implProjectList").val("").trigger("change");
//  }
  
}

function loadContractList(param){
 $('#contractList').empty();
var client = new com.im.common.ajax();
  var result = client.callAsJson("measureReportController/queryContractListByImplProject",param);
  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
    $.each( result.result, function (i) {
      $('#contractList').append("<option value=" + result.result[i].contractId + ">" +result.result[i].contractName + "</option>");

    });
    $("#contractList").select2({});
    $("#contractList").val("").trigger("change");
  }

}

function loadContractClauseList(param){
	if(param.contractId == null || param.contractId == ''){
		return false;
	}
  $('#contractClauseList').val('').attr('data-id','');
  var client = new com.im.common.ajax();
  var result = client.callAsJson("measureReportController/queryContractItemDetailByContractId",param);
  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
	  if(result.result.length != 0){
		  $('#contractClauseList').val(result.result[0].contractClauseName).attr('data-id',result.result[0].contractClauseId);
		  _searchEditList(result.result);
		  $('#contractItemModal').on('shown.bs.modal', function () {
		      $("#editList").empty();
		      _searchEditList(result.result);
		      $('#contractItemModal').unbind("shown.bs.modal");
		  });
	  }
//    result.result.unshift({'contractClauseId':'','contractClauseName':'全部'});
//    $.each( result.result, function (i) {
//      $('#contractClauseList').append("<option value=" + result.result[i].contractClauseId + ">" +result.result[i].contractClauseName + "</option>");
//
//    });
//    $("#contractClauseList").select2({});
//    $("#contractClauseList").val("").trigger("change");
  }
}
function _searchEditList(data){
	var dataList = {
			order:'asc',
			pageNumber:1,
			pageSize:100,
			rows:data,
			sort:'',
			total:1,
			totalPages:1
	};
	var columns=[[
	    {field:'contractItemName',width:100,title:"合同分项",resizable:true},
	    {field:'amount',width:80,title:"数量",resizable:true},
	    {field:'unitPrice',width:80,title:"单价",resizable:true},
	    {field:'otherCharge',width:80,title:"其它费用",resizable:true},
	    {field:'itemTotal',width:100,title:"分项总额",resizable:true},
	    {field:'paymentRatio',width:100,title:"已支付比例",resizable:true},
	    {field:'payment',width:100,title:"已支付金额",resizable:true},
	    {field:'nowPaymentRatio',width:100,title:"本次支付比例",
	    	editor:{
	    		type:'numberbox',
	    		options:{
	    			precision:2,
	    			min:0,
	    			max:100
	    		}
	    	},
	    resizable:true},
	    {field:'nowPayment',width:100,title:"本次支付金额",resizable:true},
	    {field:'description',width:150,title:"备注",editor:'text',resizable:true},
	    {field:'operation',title:"操作",width:100,width:100,align:'center',resizable:true,
	        formatter: function(value,row,index){
	        	return	'<a href="javascript:; "onclick="_edit(this)" title="修改"><i class="fa fa-edit"></i></a>'+
        				'<a href="javascript:; "onclick="_save('+index+',this)" title="保存" style="display:none;"><i class="fa fa-check-square-o"></i></a>'+
        				'<a href="javascript:; "onclick="_cancel(this)" title="取消" style="display:none;"><i class="fa fa-refresh"></i></a>';
	    }
//	        formatter: function(value,row,index){
//	            return  '<a href="javascript:; "onclick="fnDetailList()" >详情</a> ';
//	    }
	    },
	    {field:'more',title:"更多",width:100,width:100,align:'center',resizable:true,
	        formatter: function(value,row,index){
	            return  '<a href="javascript:; "onclick="fnDetailList()" >详情</a> ';
	    }}
	]];
	var param={
    		pageNumber: 1,
    		pageSize: 100
    	};
    	$('#editList').datagrid({
    	    method:'post',
    	    dataType : 'json',
    	    nowrap:false,
    	    fitColumns:true,
    	    columns:columns,
    	    data:dataList,
    	    onLoadSuccess: function(data){                 
    	    	
    	    }
    	});
    	$('#editList').datagrid('mergeCells', {  
            index: 0,  
            field: 'more',  
            rowspan: data.length,  
            colspan: null  
        });
}
//编辑操作
function _edit(target){
	$('#editList').datagrid('beginEdit', _getRowIndex(target));
	$(target).hide().next().show();
	$(target).next().next().show();
}
//取消操作
function _cancel(target){
	$('#editList').datagrid('cancelEdit', _getRowIndex(target));
}
//保存操作
function _getRowIndex(target){
	var tr = $(target).closest('tr.datagrid-row');
	return parseInt(tr.attr('datagrid-row-index'));
}
function _save(index,target){
	com.im.common.confirm("确定要保存吗？", null, function () {
    	$('#editList').datagrid('endEdit', _getRowIndex(target));
    	$(target).hide().prev().show();
    	$(target).next().hide();
    	var editList = $('#editList').datagrid('getData').rows[index];
	    var saveparam={
	    	declareId : editList.declareId,
	    	nowPaymentRatio : editList.nowPaymentRatio,
	    	nowPayment : editList.nowPaymentRatio*editList.itemTotal/100,
	    	description : editList.description,
	    	contractItemId : editList.contractItemId,
	    	amount : editList.amount,
	    	itemTotal : editList.itemTotal,
	    	paymentRatio : editList.paymentRatio,
	    	payment : editList.paymentRatio*editList.itemTotal/100,
	    };
	    if(editList.payId && editList.payId !=''){
	    	saveparam.payId = editList.payId;
	    }
	    var client = new com.im.common.ajax();
	    var result = client.callAsJson("measureReportController/updateDeclarePay", saveparam);
	    if(result.resultCode=='0'){
	    	toastr.success("保存成功");
	    	loadContractClauseList({contractId: $('#contractList').val()});
	    	queryMeasureList();
	    }else {
	        toastr.error('请稍后再试！'+result.resultMsg);
	    }
	});
}
//明细
function fnDetailList(){
	$('#detailImpleProjName').html($("#implProjectList option:selected").html());
	$('#detailContractName').html($("#contractList option:selected").html());
	$('#searchContractClauseName').html($('#contractClauseList').val());
	$('#detailModal').modal("show");
}
function _searchDetailList(param){
	var columns=[[
	    {field:'contractItemName',width:100,title:"合同分项",rowspan:2,resizable:true},
	    {field:'amonut',title:"数量",width:80,rowspan:2,resizable:true},
	    {field:'unitPrice',title:"单价",width:80,rowspan:2,resizable:true},
	    {field:'otherCharge',title:"其它费用",width:80,rowspan:2,resizable:true},
	    {field:'itemTotal',title:"分项总额",width:80,rowspan:2,resizable:true}
	],[]];
	var client = new com.im.common.ajax();
	var result = client.callAsJson("metePayService/queryMetePayStaticDetailList", param);
	var num = 0;
	$.each(result.result.rows,function (index,item){
		if((item.metePayList).length > num){
			num = (item.metePayList).length;
		}
	});
	for(var i =0;i<num;i++){
		columns[0].push({field:'pay',title:"第"+(i+1)+"次支付",width:100,colspan:3,resizable:true});
		var payment = {
			field:'payment'+i,
			title:"支付金额",
			width:80,
			resizable:true,
    		formatter: function(value,row,index){
    			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
    			if((row.metePayList)[nowNum]){
    				return (row.metePayList)[nowNum].payment;
    			}else{
    				return '';
    			}
    	    }
		};
		var payRatio = {
    			field:'payRatio'+i,
    			title:"支付比例",
    			width:80,
    			resizable:true,
        		formatter: function(value,row,index){
        			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
        			if((row.metePayList)[nowNum]){
        				return (row.metePayList)[nowNum].payRatio;
        			}else{
        				return '';
        			}
        	    }
    		};
		var payDt = {
    			field:'payDt'+i,
    			title:"申请时间",
    			width:80,
    			resizable:true,
        		formatter: function(value,row,index){
        			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
        			if((row.metePayList)[nowNum]){
        				return (row.metePayList)[nowNum].payDt;
        			}else{
        				return '';
        			}
        	    }
    		};
		columns[1].push(payment);
		columns[1].push(payRatio);
		columns[1].push(payDt);
	}
	$('#detailList').datagrid({
	    method:'post',
	    dataType : 'json',
	    queryParams:param,
	    pagination:true,
	    nowrap:false,
	    fitColumns:true,
	    columns:columns,
	    loadMsg:'数据加载中，请耐心等待',
	    data:result.result
	});
	var p = $('#detailList').datagrid('getPager');
  	  $(p).pagination({
  	    pageSize: 20,
  	    pageList: [10,20,30],
  	    beforePageText: '第',
  	    afterPageText: '页    共 {pages}  页',
  	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
  	    onSelectPage:function(pageNumber, pageSize){
  	    	var param={
  	      		pageInfo:{
  	      			pageNumber: pageNumber,
  	          		pageSize: pageSize,
  	      		},
  	      		contractId:countStatic.contractId
  	      	};
  	    	_searchDetailList(param);
  	    }
  	  });
}

function loadContractItemList(param){
  $('#contractItemList').empty();
var client = new com.im.common.ajax();
  var result = client.callAsJson("measureReportController/queryContractItemListByContractClause",param);
  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
     result.result.unshift({'contractItemId':'','contractItemName':'全部'});
    $.each( result.result, function (i) {
      $('#contractItemList').append("<option value=" + result.result[i].contractItemId + ">" +result.result[i].contractItemName + "</option>");

    });
    $("#contractItemList").select2({});
    $("#contractItemList").val("").trigger("change");
  }
}

function showItemInfo(param){
var client = new com.im.common.ajax();
  var result = client.callAsJson("measureReportController/queryContractItemInfo",param);
  if(!result.success){
      toastr.error(result.resultMsg);
    }else{
          if(result.result!=null && result.result.length>0){
                    $("#amount").val(result.result[0].amount);
                    $("#total").val(result.result[0].total);
                    $("#unitPrice").val(result.result[0].unitPrice);
                  //  $("#payment").val(result.result[0].payment);
                    $("#availableAmount").val(result.result[0].total-result.result[0].payment);

          }
    }
}

function initOrg(){
  var client = new com.im.common.ajax();
  var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","orgType":10});

  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
    result.result.unshift({'orgId':'','orgName':'全部'});
    $.each( result.result, function (i) {
      $('#orgId').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

    });
    $("#orgId").select2({});
  }
}

$(function(){
  initTable();

  $("#orgId").project2unit2itemCommpent({
    //elmIdProjectSel : "projectSel",//规划工程下拉元素
    elmIdPlanTypeSel : "planProjClass",
    elmIdUnitSel : "orgId",//组织单位下拉元素
    elmIdItemSel : "implProjectId",//实施项目下拉元素
    orgType : "10",//初始化单位时，单位类型
    callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
      //_callBackOrg(objvalue, objname);
      //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
      //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
      queryMeasureList();
    }
  });

  $("#search-btn").click(function(){
    queryMeasureList();
  });

  $("#btn_reset").click(function(){
    reset();
  });

  $("#btn_add").click(function(){
    $('#contractItemModal').modal({
      backdrop: false,//点击空白处不关闭对话框
      keyboard: false,//键盘关闭对话框
      show:true//弹出对话框
    });
  });

  $('#contractItemModal').on('hidden.bs.modal', function () {
	$("#implProjectList").val("").trigger("change");
    $("#contractList").val("").trigger("change");
    $("#contractClauseList").val("").attr('data-id','');
    $("#contractItemList").val("").trigger("change");
    $("#amount").val("");
    $("#unitPrice").val("");
    $("#payment").val("");
    $("#declareId").val("");
    $("#total").val("");
    oldPayment=null;
    availableModelField();
    $('#contractItemForm').data('bootstrapValidator').options.excluded = [':disabled'];
    $('#contractItemForm').bootstrapValidator('resetForm', true);
    $('#contractItemForm')[0].reset();
    $('#editList').datagrid('loadData',{total:0,rows:[]});
  });

//  $('#contractItemModal').on('shown.bs.modal', function () {
//      $("#editList").empty();
//      _searchEditList();
//  });
  $('#detailModal').on('shown.bs.modal', function () {
      $("#detailList").empty();
      var param={
	      		pageInfo:{
	      			pageNumber: 1,
	          		pageSize: 20,
	      		},
	      		contractId:$('#contractList option:selected').attr("value")
	      	};
      _searchDetailList(param);
  });
  $("#giveDt").daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        drops:'up',
        locale: {
          format: 'YYYY-MM-DD HH:mm:ss',
          daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
          monthNames: ['一月', '二月','三月', '三月', '四月', '五月','六月', '七月', '八月','九月','十月','十一月','十二月'],
        },
        timePicker: true,
        timePicker24Hour: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        timePickerIncrement: 1,
        minDate:moment('2017-01-01 00:00:00'),
      },
      function (start, end, label) {
      }
  );

  $("#ensureBtn").click(function () {
    saveMeasureReport();
  });

  $("#payment").on("input propertychange",function(){
     var total=$("#total").val();
     if(total==null || total==''){
        toastr.warning("请先现在完项目信息后再填写支付金额");
        $(this).val('');
     }else{
       $("#paymentRatio").val($(this).val()/total*100);
     }
  });

  initProjectList();

  $("#implProjectList").bind('change', function () {
       loadContractList({impleProjId: $(this).val()});
   });

   $("#contractList").bind('change', function () {
          loadContractClauseList({contractId: $(this).val()});
    });

   $("#contractClauseList").bind('change', function () {
          loadContractItemList({contractClauseId: $(this).val()});
   });

    $("#contractItemList").bind('change', function () {
        showItemInfo({contractItemId: $(this).val()});
    });




  $("#contractItemForm").bootstrapValidator({
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-loadData'
    },
    excluded: [':disabled', ':hidden', ':not(:visible)'],
    fields: {
      implProjectList: {
        validators: {
          notEmpty: {
            message: '请选择实施项目'
          }
        }
      },
      contractList: {
        validators: {
          notEmpty: {
            message: '请选择合同'
          }
        }
      },
      contractClauseList: {
        validators: {
          notEmpty: {
            message: '请选择合同条款'
          }
        }
      },
      contractItemList: {
        validators: {
          notEmpty: {
            message: '请选择合同分项'
          }
        }
      },
      payment:{
              validators: {
                notEmpty: {
                  message: '预算总价不能为空'
                },
            regexp: {
                                        regexp: /^[1-9][0-9]*(\.[0-9]{1,2})?$|^[0](\.[0-9]{1,2})?$/,
                                        message:"必须为保留2为小数的正整数"
             },
            callback: {/*自定义，可以在这里与其他输入项联动校验*/
                 message: '必须小于可申请金额',
                 callback:function(value, validator,$field){
                     return parseFloat(value)<=parseFloat($("#availableAmount").val());
                 }
             }
              }
      },
  }
  });

})